#include "bootstrap.h"

#define IPV4_ADDRESS_LEN 	40
#define IPV4_PORT_LEN		10

#include <string.h>

//reverse string s in place
void reverse(char s[])
{
    int c, i, j;

    for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

//convert n to characters in s
void itoa(int n, char s[])		//thanks to Kernighan and Ritchie
{
    int i, sign;

    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}

//esegue il parsing di [indirizzo:porta] contenuto nella stringa s, copiando l'indirizzo in *a e la porta in *p
void parse_ipv4_address(char *s, char *a, int *p) {	//assuming a terminated '\0' source string and an allocated destination string
	char *d;
	d = strchr(s, ':');
	int l = d-s;
	d++;
	
	int port;
	port = atoi(d);
	*p = port;
	strncpy(a, s, l);
}

//rimuove l'ultima linea vuora da una stringa
void remove_last_newline(char *s) {
	int l = strlen(s)-1;
	if(s[l]=='\n')
		s[l] = '\0';
	return;
}

//legge la lista di bootstrap ed aggiunge i peer alla nodecache
void get_bootstrap_list(char *filename) {
	FILE *f;
	char buffer[100];
	char *s;
	
	f = fopen(filename, "r");
	if(f<0)
		handle_error("impossibile aprire bootstrap list");
		
	while(!feof(f))
		if(fgets(buffer, 99, f)!=NULL) {
			remove_last_newline(buffer);
			if(strlen(buffer)>0) {
				verbose2("parsing %s\n", buffer);
				add_node_boot(buffer, 0, CONNECTION_TYPE_CONNECT);
			}
		}
	fclose(f);
}

FILE *bootstrap_file;

void init_bootstrap_list(char *filename) {
	bootstrap_file = fopen(filename, "r");
	if(bootstrap_file<0)
		handle_error("impossibile aprire bootstrap list");
}

void add_node_from_bootstrap() {
	node *n;
	char buffer[256];
	if(fgets(buffer, 99, bootstrap_file)!=NULL) {
		remove_last_newline(buffer);
		if(strlen(buffer)>0) {
			verbose2("parsing %s\n", buffer);
			n=add_node_boot(buffer, 0, CONNECTION_TYPE_CONNECT);
			return n;
		}
	}
	return NULL;
}



//salva la lista di peer contenuti nella nodecache
void save_bootstrap_list(char *filename) {
	FILE *f;
	node *n;
	char port[IPV4_PORT_LEN];

	f = fopen(filename, "w+");
	if(f<0)
		handle_error("impossibile salvare bootstrap list");
	
	
	printf("saving nodecache..\n");
	for_each_node(n) {
		fwrite(n->c->address, sizeof(char), strlen(n->c->address), f);
		fwrite(":", sizeof(char), 1, f);
		itoa(n->c->listening_port, port);
		fwrite(port, sizeof(char), strlen(port), f);
		fwrite("\n", sizeof(char), 1, f);
	}
	
	printf("saving peerlist..\n");
	g_hash_table_foreach(peerlist, peerlist_to_FILE, f);
	
	fclose(f);
}

